package com.shuohe.service.util.sql;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shuohe.util.autoid.AutoIdBean;
import com.shuohe.util.date.SDate;

@Service
public class AutoIdServiceImpl {
//	@Autowired // 注解
//	private HibernateTemplate ht;

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public Object getAutoObjectByAutoId(Class<?> clazz, String auto_id) {
		Object ret = new Object();
		String hql = "from " + clazz.getName()+" where auto_id="+"\'"+auto_id+"\'";
		try {
			Query query = entityManager.createQuery(hql);
			Iterator its= query.getResultList().iterator();
			while (its.hasNext()) {
				ret = (Object) its.next();
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return ret;
	}

	@Transactional
	public String getOrderId(AutoIdBean clazz, String base, String header_name) {
		String day = SDate.getSystemDateYMDToString();
		String ret = null;
		long id = getOrderIdForOneDay(clazz.getClass().getName(), base, day);
		id++;
		String xs = String.valueOf(id);
		String[] ss = { "0000", "000", "00", "0", "" };
		xs = ss[xs.length() + 1] + xs;
		ret = header_name + "-" + SDate.getSystemDateYMD2ToString() + "-" + xs;
		clazz.setAuto_id(ret);
		clazz.setDate(SDate.getSystemDate());
		insert(clazz);
		return ret;
	}

	@Transactional
	private long getOrderIdForOneDay(String clazz, String base, String day) {
		long ret = 0;
		String start = day + " 00:00:00";
		String end = day + " 23:59:59";
		try {

			String hql = "select p." + base + " from " + clazz + " as" + " p where p.date >='" + start
					+ "' and p.date <='" + end + "'" + " order by p." + base + " desc";

			Query query = entityManager.createQuery(hql);
			List<?> its= query.getResultList();
			// debug("len="+its.size());

			String temp = null;
			for (Object s : its) {
				// debug("s = "+s);
				temp = (String) s;
				break;
			}
			if (temp != null) {
				ret = Long.parseLong(temp.substring(temp.length() - 3, temp.length()));
				// debug("ret = "+ret);
			} else if (temp == null) {
				ret = 0;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return ret;
	}

	@Transactional
	private void insert(Object object) {
		try {
			entityManager.persist(object);
			entityManager.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}
}
